package com.gzxw.mogublog.xo.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzxw.mogublog.base.global.BaseSysConf;
import com.gzxw.mogublog.base.holder.RequestHolder;
import com.gzxw.mogublog.commons.entity.Admin;
import com.gzxw.mogublog.commons.entity.File;
import com.gzxw.mogublog.commons.entity.Role;
import com.gzxw.mogublog.commons.feign.PictureFeignClient;
import com.gzxw.mogublog.utils.*;
import com.gzxw.mogublog.xo.global.RedisConf;
import com.gzxw.mogublog.xo.mapper.AdminMapper;
import com.gzxw.mogublog.xo.service.AdminService;
import com.gzxw.mogublog.xo.service.RoleService;
import com.gzxw.mogublog.xo.vo.AdminVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Autowired
    private RoleService roleService;


    // 1.根据管理员id查询管理
    @Override
    public Admin getAdminById(String adminUid) {

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", adminUid);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void addOnlineAdmin(Admin admin, Long expirationSecond) {

        // 首先取出请求，为取出ip做准备
   /*     HttpServletRequest request = RequestHolder.getRequest();
        // 根据请求拿到浏览器，系统等信息
        Map<String, String> map = IpUtils.getOsAndBrowserInfo(request);
        // 获取浏览器，操作系统，当前用户ip
        String os = map.get(BaseSysConf.OS);
        String browser = map.get(BaseSysConf.BROWSER);
        String ip = IpUtils.getIpAddr(request);
        // 给在线对象设置值
        OnlineAdmin onlineAdmin = new OnlineAdmin();
        onlineAdmin.setAdminUid(admin.getUid());
        onlineAdmin.setTokenId(admin.getTokenUid());
        onlineAdmin.setToken(admin.getValidCode());
        onlineAdmin.setOs(os);
        onlineAdmin.setBrowser(browser);
        onlineAdmin.setIpaddr(ip);
        onlineAdmin.setLoginTime(DateUtils.getNowTime());
//        onlineAdmin.setRoleName(admin.getRole().getRoleName());
        onlineAdmin.setUserName(admin.getUserName());
        onlineAdmin.setExpireTime(DateUtils.getDateStr(new Date(), expirationSecond));

        // 在维护一张表，用于 uuid - token 互相转换
        redisUtil.setEx(RedisConf.LOGIN_UUID_KEY + RedisConf.SEGMENTATION + admin.getTokenUid(),JsonUtils.objectToJson(onlineAdmin), expirationSecond, TimeUnit.SECONDS);
*/
    }

    @Override
    public IPage<Admin> getList(AdminVO adminVO) {

        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(adminVO.getKeyword())) {
            adminQueryWrapper.like("user_name", adminVO.getKeyword().trim());
        }
        Page<Admin> page = new Page<>(); // 分页
        page.setCurrent(adminVO.getCurrentPage());
        page.setSize(adminVO.getPageSize());
        // 忽略密码
        adminQueryWrapper.select(Admin.class, i -> !i.getProperty().equals("pass_word"));
        adminQueryWrapper.eq("status", 1);

        IPage<Admin> pageList = this.page(page, adminQueryWrapper);
        List<Admin> records = pageList.getRecords();

        List<String> fileUids = new ArrayList<>();
        records.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getAvatar())) {
                fileUids.add(item.getAvatar());
            }
        });

        Map<String, String> pictureMap = new HashMap<>(10);
        R picResult = null;
        // 调用图片服务
        if (fileUids.size() > 0) {
            picResult = pictureFeignClient.getPictures(fileUids);
        }
        String data = picResult.getMessage();
        List<File> fileList = JSON.parseArray(data, File.class);

        fileList.forEach(item -> {
            pictureMap.put(item.getUid(), item.getPicUrl());
        });

        records.forEach(item -> {
            Role role = roleService.getById(item.getRoleUid());
            item.setRole(role);
            item.setPhotoList(Collections.singletonList(pictureMap.get(item.getAvatar())));
        });

        return pageList;
    }

    @Override
    public String restPwd(AdminVO adminVO) {

        String defaultPassword = "mogu2018";
        Admin admin = this.getById(adminVO.getUid());
        if ("admin".equals(admin.getUserName())) {
            return "超级管理员admin的密码仅能admin账号操作";
        } else {

            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            admin.setPassWord(passwordEncoder.encode(defaultPassword));
            admin.setUpdateTime(new Date());
            admin.updateById();
        }
        return "重置成功";
    }

    @Override
    public String addAdmin(AdminVO adminVO) {
        String mobile = adminVO.getMobile(); // 手机号
        String userName = adminVO.getUserName(); // 用户名
        String email = adminVO.getEmail(); // 邮箱
        if (StringUtils.isEmpty(userName)) {
            return "参数有误!";
        }
        if (StringUtils.isEmpty(email) && StringUtils.isEmpty(mobile)) {
            return "邮箱和手机号至少一项不能为空";
        }
        // 默认密码
        String defaultPassword = "mogu2018";
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);

        Admin temp = this.getOne(queryWrapper);

        if (temp != null) {
            return "该实体已经存在";
        }

        Admin admin = new Admin();
        admin.setAvatar(adminVO.getAvatar());
        admin.setEmail(adminVO.getEmail());
        admin.setGender(adminVO.getGender());
        admin.setUserName(adminVO.getUserName());
        admin.setNickName(adminVO.getNickName());
        admin.setRoleUid(adminVO.getRoleUid());
        // 设置为未审核状态
        admin.setStatus(1);
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        admin.setPassWord(passwordEncoder.encode(defaultPassword));

        this.save(admin);

        return "实体添加成功";
    }

    @Override
    public String editAdmin(AdminVO adminVO) {
        Admin admin = this.getById(adminVO.getUid());

        /*if ("admin".equals(adminVO.getUserName())) {
            return "超级管理员用户名必须为admin";
        }*/

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("user_name", adminVO.getUserName());
        List<Admin> list = this.list(queryWrapper);
        if (list.size() > 1 || !adminVO.getUid().equals(list.get(0).getUid())) {
            return "修改失败，该实体已经存在";
        }

        //TODO 判断是否更改了RoleUid，更新redis中admin的URL访问路径
        admin.setUserName(adminVO.getUserName());
        admin.setAvatar(adminVO.getAvatar());
        admin.setNickName(adminVO.getNickName());
        admin.setGender(adminVO.getGender());
        admin.setEmail(adminVO.getEmail());
        admin.setQqNumber(adminVO.getQqNumber());
        admin.setGithub(adminVO.getGithub());
        admin.setGitee(adminVO.getGitee());
        admin.setOccupation(adminVO.getOccupation());
        admin.setUpdateTime(new Date());
        admin.setMobile(adminVO.getMobile());
        admin.setRoleUid(adminVO.getRoleUid());
        // 无法直接修改密码，只能通过重置密码完成密码修改
        admin.updateById();

        return "操作成功";
    }

    @Override
    public String deleteBatchAdmin(List<String> adminUids) {
        if (adminUids.size()<=0) {
            return "请选择要删除的管理员";
        }

        List<Admin> adminList = new ArrayList<>();
        adminUids.forEach(item -> {
            Admin admin = new Admin();
            admin.setUid(item);
            admin.setStatus(0);
            admin.setUpdateTime(new Date());
            adminList.add(admin);
        });
        this.updateBatchById(adminList);
        return "批量删除成功";
    }
}
